from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from main.views import SearchBar
from auth.forms import loginForm, RegistrationForm
from main.models import Outcrop

"""
View to allow a user to log in.
""" 
def login_user(request):
    form = loginForm()
    state= ""
    if request.method == 'POST':
        form = loginForm(request.POST)
        if form.is_valid():
            username  = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username,password=password)
            if (user is not None) and (not user.is_anonymous()):
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect('/user/')
                else:
                    state = "Your account is not active, please contact the site admin."
            else:
                state = "Your email and/or password was incorrect."
    searchForm = SearchBar()
    outcrop_list = Outcrop.objects.all()
    return render_to_response('main/index.html',{'title':'Home', 'searchForm':searchForm, 'loginForm':form, 'state':state, 'outcrop_list':outcrop_list, 'onLoad':'init()'}, context_instance=RequestContext(request))

"""
View to register a new user.
""" 
def register_user(request):
    form = RegistrationForm()
    state = ""
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            if form.cleaned_data['password'] == form.cleaned_data['password2']:
                try:
                    #attempt to retrieve the username, if it can be retrieved then show an error as the username already exists
                    User.objects.get(username=form.cleaned_data['username'])
                    state = 'This username is already in use, please use a different username.'
                except User.DoesNotExist:
                    User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'])
                    user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
                    login(request, user)
                    return HttpResponseRedirect('/user/')
            else:
                state = 'Your password was not the same. Please re-enter your password.'
    searchForm = SearchBar()
    return render_to_response('auth/registration.html',{'title':'Registration','state':state, 'searchForm':searchForm, 'form':form}, context_instance=RequestContext(request))

def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse('home'))
